package org.quickserver.net.qsadmin;

import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.pool.ObjectPool;
import org.quickserver.net.AppException;
import org.quickserver.net.server.ClientCommandHandler;
import org.quickserver.net.server.ClientEventHandler;
import org.quickserver.net.server.ClientHandler;
import org.quickserver.net.server.ClientIdentifier;
import org.quickserver.net.server.QuickServer;
import org.quickserver.util.JvmUtil;
import org.quickserver.util.MyString;
import org.quickserver.util.pool.PoolHelper;
import org.quickserver.util.pool.QSObjectPool;
import org.quickserver.util.pool.thread.ClientThread;

public class CommandHandler
  implements ClientCommandHandler, ClientEventHandler
{
  private static Logger logger = Logger.getLogger(CommandHandler.class.getName());
  
  private static Format formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
  
  private static File getFile(String name, String ext) {
    StringBuilder sb = new StringBuilder("./");
    
    File logDir = new File("./log/");
    if (!logDir.exists()) {
      logDir.mkdirs();
    }
    if (logDir.canWrite()) {
      sb.append("log/");
    }
    
    sb.append(name);
    sb.append("_");
    sb.append(formatter.format(new Date()));
    
    sb.append(ext);
    
    return new File(sb.toString());
  }
  
  private CommandPlugin plugin;
  private Runtime runtime;
  StringBuilder temp = new StringBuilder();


  
  public void gotConnected(ClientHandler handler) throws SocketTimeoutException, IOException {
    logger.log(Level.FINE, "Connection opened : {0}", handler.getHostAddress());
    
    handler.sendClientMsg("+OK +++++++++++++++++++++++++++++++++");
    handler.sendClientMsg("+OK   Welcome to QsAdminServer v 1.0 ");
    handler.sendClientMsg("+OK +++++++++++++++++++++++++++++++++");

    
    if (this.plugin == null || this.runtime == null) {
      this.plugin = 
        (CommandPlugin)handler.getServer().getStoreObjects()[1];
      
      this.runtime = Runtime.getRuntime();
    } 
  }


  
  public void lostConnection(ClientHandler handler) throws IOException { logger.log(Level.FINE, "Connection lost : {0}", handler.getHostAddress()); }


  
  public void closingConnection(ClientHandler handler) throws IOException { logger.log(Level.FINE, "Connection closing : {0}", handler.getHostAddress()); }



  
  public void handleCommand(ClientHandler handler, String command) throws SocketTimeoutException, IOException {
    if (command == null || command.trim().equals("")) {
      handler.sendClientMsg("-ERR No command");
      
      return;
    } 
    
    if (this.plugin != null && this.plugin.handleCommand(handler, command)) {
      logger.fine("Handled by plugin.");
      return;
    } 
    QSAdminServer adminServer = 
      (QSAdminServer)handler.getServer().getStoreObjects()[2];
    
    StringTokenizer st = new StringTokenizer(command, " ");
    String cmd = null;
    cmd = st.nextToken().toLowerCase();
    String[] param = new String[st.countTokens()];
    
    QuickServer target = null;
    for (int i = 0; st.hasMoreTokens(); i++) {
      param[i] = st.nextToken();
    }
    
    if (command.equals("start console")) {
      QSAdminShell.getInstance(
          (QuickServer)handler.getServer().getStoreObjects()[0], null);
      handler.sendClientMsg("+OK QSAdminShell is started."); return;
    } 
    if (command.equals("stop console")) {
      QSAdminShell shell = QSAdminShell.getInstance(null, null);
      if (shell != null) {
        try {
          shell.stopShell();
        } catch (Exception err) {
          handler.sendClientMsg("-ERR Error stopping QSAdminShell: " + err);
        } 
        handler.sendClientMsg("+OK QSAdminShell is stopped.");
      } else {
        handler.sendClientMsg("-ERR QSAdminShell is not running.");
      }  return;
    } 
    if (cmd.equals("jvm")) {









      
      if (param.length == 0) {
        handler.sendClientMsg("-ERR Use jvm help");
        
        return;
      } 
      if (param[0].equals("dumpHeap")) {
        File file = getFile("dumpHeap", ".bin");
        JvmUtil.dumpHeap(file.getAbsolutePath(), true);
        handler.sendClientMsg("+OK File " + file.getAbsolutePath());
      } else if (param[0].equals("dumpJmapHisto")) {
        if (param.length < 2) {
          handler.sendClientMsg("-ERR insufficient param");
          
          return;
        } 
        if (param[1].equals("file")) {
          File file = getFile("dumpJmapHisto", ".txt");
          
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.dumpJmapHisto(file.getAbsolutePath());
          
          handler.sendClientMsg("Done - File " + file.getAbsolutePath());
          handler.sendClientMsg(".");
        } else if (param[1].equals("log")) {
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.dumpJmapHistoToLog();
          
          handler.sendClientMsg("Done - Dumped to jdk log file");
          handler.sendClientMsg(".");
        } else {
          handler.sendClientMsg("-ERR bad param");
          return;
        } 
      } else if (param[0].equals("threadDump")) {
        if (param.length < 2) {
          handler.sendClientMsg("-ERR insufficient param");
          
          return;
        } 
        if (param[1].equals("file")) {
          File file = getFile("threadDump", ".txt");
          
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.threadDump(file.getAbsolutePath());
          
          handler.sendClientMsg("Done - File " + file.getAbsolutePath());
          handler.sendClientMsg(".");
        } else if (param[1].equals("log")) {
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.threadDumpToLog();
          
          handler.sendClientMsg("Done - Dumped to jdk log file");
          handler.sendClientMsg(".");
        } else {
          handler.sendClientMsg("-ERR bad param");
          return;
        } 
      } else if (param[0].equals("dumpJStack")) {
        if (param.length < 2) {
          handler.sendClientMsg("-ERR insufficient param");
          
          return;
        } 
        if (param[1].equals("file")) {
          File file = getFile("dumpJStack", ".txt");
          
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.dumpJStack(file.getAbsolutePath());
          
          handler.sendClientMsg("Done - File " + file.getAbsolutePath());
          handler.sendClientMsg(".");
        } else if (param[1].equals("log")) {
          handler.sendClientMsg("+OK info follows");
          handler.sendClientMsg("Starting.. ");
          
          JvmUtil.dumpJStackToLog();
          
          handler.sendClientMsg("Done - Dumped to jdk log file");
          handler.sendClientMsg(".");
        } else {
          handler.sendClientMsg("-ERR bad param"); return;
        } 
      } else {
        if (param[0].equals("help")) {
          handler.sendClientMsg("+OK info follows");
          
          handler.sendClientMsg("jvm dumpJmapHisto file");
          handler.sendClientMsg("jvm dumpJStack file");
          
          handler.sendClientMsg(" ");
          
          handler.sendClientMsg("jvm threadDump file");
          handler.sendClientMsg("jvm dumpHeap");
          
          handler.sendClientMsg(" ");
          
          handler.sendClientMsg("jvm threadDump log");
          handler.sendClientMsg("jvm dumpJmapHisto log");
          handler.sendClientMsg("jvm dumpJStack log");
          
          handler.sendClientMsg(".");
          return;
        } 
        handler.sendClientMsg("-ERR bad param use jvm help");
      } 
      
      return;
    } 
    if (param.length > 0) {
      if (param[0].equals("server")) {
        target = (QuickServer)handler.getServer().getStoreObjects()[0];
      } else if (param[0].equals("self")) {
        target = handler.getServer();
      } else {
        handler.sendClientMsg("-ERR Bad <<target>> : " + param[0]);
        
        return;
      } 
    }
    if (cmd.equals("help")) {
      handler.sendClientMsg("+OK info follows\r\nRefer Api Docs for org.quickserver.net.qsadmin.CommandHandler");
      
      handler.sendClientMsg("."); return;
    } 
    if (cmd.equals("quit")) {
      handler.sendClientMsg("+OK Bye ;-)");
      handler.closeConnection(); return;
    } 
    if (cmd.equals("shutdown")) {
      try {
        QuickServer controlServer = 
          (QuickServer)handler.getServer().getStoreObjects()[0];
        if (controlServer != null && !controlServer.isClosed()) {
          controlServer.stopServer();
        }
        if (handler.getServer() != null && !handler.getServer().isClosed()) {
          handler.getServer().stopServer();
        }
        
        QSAdminShell shell = QSAdminShell.getInstance(null, null);
        if (shell != null) {
          try {
            shell.stopShell();
          } catch (Exception err) {
            logger.warning("Error stoping shell: " + err);
          } 
        }
        
        handler.sendClientMsg("+OK Done");
      } catch (AppException e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("version")) {
      handler.sendClientMsg("+OK " + QuickServer.getVersion()); return;
    } 
    if (cmd.equals("kill") || cmd.equals("exit")) {
      StringBuilder errBuf = new StringBuilder();
      QuickServer controlServer = 
        (QuickServer)handler.getServer().getStoreObjects()[0];
      int exitCode = 0;
      
      if (param.length != 0) {
        try {
          exitCode = Integer.parseInt(param[0]);
        } catch (Exception exception) {}
      }
      
      try {
        if (controlServer != null && !controlServer.isClosed()) {
          try {
            controlServer.stopServer();
          } catch (AppException ae) {
            errBuf.append(ae.toString());
          } 
        }
        if (handler.getServer() != null && !handler.getServer().isClosed()) {
          try {
            handler.getServer().stopServer();
          } catch (AppException ae) {
            errBuf.append(ae.toString());
          } 
        }
        
        QSAdminShell shell = QSAdminShell.getInstance(null, null);
        if (shell != null) {
          try {
            shell.stopShell();
          } catch (Exception err) {
            errBuf.append(err.toString());
          } 
        }
        
        if (errBuf.length() == 0)
        { handler.sendClientMsg("+OK Done"); }
        else
        { handler.sendClientMsg("+OK Done, Errors: " + errBuf.toString()); } 
      } catch (Exception e) {
        handler.sendClientMsg("-ERR Exception : " + e + "\r\n" + errBuf.toString());
        if (exitCode == 0) exitCode = 1; 
      } finally {
        try {
          if (controlServer != null)
            controlServer.closeAllPools(); 
          if (handler.getServer() != null)
            handler.getServer().closeAllPools(); 
        } catch (Exception er) {
          logger.warning("Error closing pools: " + er);
        } 
        System.exit(exitCode);
      }  return;
    } 
    if (cmd.equals("memoryinfo")) {
      
      float totalMemory = (float)this.runtime.totalMemory();
      float usedMemory = totalMemory - (float)this.runtime.freeMemory();
      float maxMemory = (float)this.runtime.maxMemory();
      handler.sendClientMsg("+OK " + totalMemory + ":" + usedMemory + ":" + maxMemory); return;
    } 
    if (cmd.equals("systeminfo")) {
      handler.sendClientMsg("+OK info follows");
      handler.sendClientMsg(MyString.getSystemInfo(QuickServer.getVersion()));
      handler.sendClientMsg("."); return;
    } 
    if (param.length == 0) {
      handler.sendClientMsg("-ERR Bad Command or No Param : ->" + cmd + "<-");
      
      return;
    } 
    if (cmd.equals("start")) {
      try {
        target.startServer();
        handler.sendClientMsg("+OK Server Started");
      } catch (AppException e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("stop")) {
      try {
        target.stopServer();
        handler.sendClientMsg("+OK Server Stopped");
      } catch (AppException e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("restart")) {
      try {
        target.stopServer();
        target.startServer();
        handler.sendClientMsg("+OK Server Restarted");
      } catch (AppException e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("info")) {
      handler.sendClientMsg("+OK info follows");
      handler.sendClientMsg("" + target);
      handler.sendClientMsg("Running : " + (target.isClosed() ? 0 : 1));
      handler.sendClientMsg("PID : " + QuickServer.getPID());
      handler.sendClientMsg("Max Client Allowed  : " + target.getMaxConnection());
      handler.sendClientMsg("No Client Connected : " + target.getClientCount());
      if (target.isRunningSecure()) {
        handler.sendClientMsg("Running in secure mode : " + 
            target.getSecure().getProtocol());
      } else {
        handler.sendClientMsg("Running in non-secure mode");
      } 
      handler.sendClientMsg("Server Mode : " + target.getBasicConfig().getServerMode());
      handler.sendClientMsg("QuickServer v : " + QuickServer.getVersion());
      handler.sendClientMsg("Uptime : " + target.getUptime());
      handler.sendClientMsg("."); return;
    } 
    if (cmd.equals("noclient")) {
      handler.sendClientMsg("+OK " + target.getClientCount()); return;
    } 
    if (cmd.equals("running")) {
      handler.sendClientMsg("+OK " + (target.isClosed() ? 0 : 1)); return;
    } 
    if (cmd.equals("suspendservice")) {
      handler.sendClientMsg("+OK " + target.suspendService()); return;
    } 
    if (cmd.equals("resumeservice")) {
      handler.sendClientMsg("+OK " + target.resumeService()); return;
    } 
    if (cmd.equals("client-thread-pool-info")) {
      this.temp.setLength(0);
      if (PoolHelper.isPoolOpen(target.getClientPool().getObjectPool())) {
        this.temp.append(target.getClientPool().getNumActive());
        this.temp.append(':');
        this.temp.append(target.getClientPool().getNumIdle());
      } else {
        this.temp.append("0:0");
      } 
      handler.sendClientMsg("+OK " + this.temp.toString()); return;
    } 
    if (cmd.equals("client-thread-pool-dump")) {
      if (PoolHelper.isPoolOpen(target.getClientPool().getObjectPool())) {
        handler.sendClientMsg("+OK info follows");
        ClientThread ct = null;
        synchronized (target.getClientPool().getObjectToSynchronize()) {
          Iterator<ClientThread> iterator = target.getClientPool().getAllClientThread();
          while (iterator.hasNext()) {
            ct = iterator.next();
            handler.sendClientMsg(ct.toString());
          } 
        } 
        handler.sendClientMsg(".");
      } else {
        handler.sendClientMsg("-ERR Pool Closed");
      }  return;
    } 
    if (cmd.equals("client-handler-pool-dump")) {
      
      ObjectPool objectPool = target.getClientHandlerPool();
      
      if (PoolHelper.isPoolOpen(objectPool)) {
        if (!QSObjectPool.class.isInstance(objectPool)) {
          handler.sendClientMsg("-ERR System Error!");
        }
        
        ClientIdentifier clientIdentifier = target.getClientIdentifier();
        ClientHandler foundClientHandler = null;
        synchronized (clientIdentifier.getObjectToSynchronize()) {
          Iterator<ClientHandler> iterator = clientIdentifier.findAllClient();
          handler.sendClientMsg("+OK info follows");
          while (iterator.hasNext()) {
            foundClientHandler = iterator.next();
            handler.sendClientMsg(foundClientHandler.info());
          } 
        } 
        handler.sendClientMsg(".");
      } else {
        handler.sendClientMsg("-ERR Pool Closed");
      }  return;
    } 
    if (cmd.equals("client-data-pool-info")) {
      this.temp.setLength(0);
      if (target.getClientDataPool() != null) {
        if (PoolHelper.isPoolOpen(target.getClientDataPool())) {
          this.temp.append(target.getClientDataPool().getNumActive());
          this.temp.append(':');
          this.temp.append(target.getClientDataPool().getNumIdle());
          handler.sendClientMsg("+OK " + this.temp.toString());
        } else {
          handler.sendClientMsg("-ERR Client Data Pool Closed");
        } 
      } else {
        handler.sendClientMsg("-ERR No Client Data Pool");
      }  return;
    } 
    if (cmd.equals("byte-buffer-pool-info")) {
      this.temp.setLength(0);
      if (target.getByteBufferPool() != null) {
        if (PoolHelper.isPoolOpen(target.getByteBufferPool())) {
          this.temp.append(target.getByteBufferPool().getNumActive());
          this.temp.append(':');
          this.temp.append(target.getByteBufferPool().getNumIdle());
          handler.sendClientMsg("+OK " + this.temp.toString());
        } else {
          handler.sendClientMsg("-ERR ByteBuffer Pool Closed");
        } 
      } else {
        handler.sendClientMsg("-ERR No ByteBuffer Pool");
      }  return;
    } 
    if (cmd.equals("all-pool-info")) {
      handler.sendClientMsg("+OK info follows");
      this.temp.setLength(0);
      
      if (PoolHelper.isPoolOpen(target.getClientPool().getObjectPool())) {
        this.temp.append("Client Thread Pool - ");
        this.temp.append("Num Active: ");
        this.temp.append(target.getClientPool().getNumActive());
        this.temp.append(", Num Idle: ");
        this.temp.append(target.getClientPool().getNumIdle());
        this.temp.append(", Max Idle: ");
        this.temp.append(target.getClientPool().getPoolConfig().getMaxIdle());
        this.temp.append(", Max Active: ");
        this.temp.append(target.getClientPool().getPoolConfig().getMaxActive());
      } else {
        this.temp.append("Byte Buffer Pool - Closed");
      } 
      handler.sendClientMsg(this.temp.toString());
      this.temp.setLength(0);
      
      if (PoolHelper.isPoolOpen(target.getClientHandlerPool())) {
        this.temp.append("Client Handler Pool - ");
        this.temp.append("Num Active: ");
        this.temp.append(target.getClientHandlerPool().getNumActive());
        this.temp.append(", Num Idle: ");
        this.temp.append(target.getClientHandlerPool().getNumIdle());
        this.temp.append(", Max Idle: ");
        this.temp.append(target.getBasicConfig().getObjectPoolConfig().getClientHandlerObjectPoolConfig().getMaxIdle());
        this.temp.append(", Max Active: ");
        this.temp.append(target.getBasicConfig().getObjectPoolConfig().getClientHandlerObjectPoolConfig().getMaxActive());
      } else {
        this.temp.append("Client Handler Pool - Closed");
      } 
      handler.sendClientMsg(this.temp.toString());
      this.temp.setLength(0);
      
      if (target.getByteBufferPool() != null) {
        if (PoolHelper.isPoolOpen(target.getByteBufferPool())) {
          this.temp.append("ByteBuffer Pool - ");
          this.temp.append("Num Active: ");
          this.temp.append(target.getByteBufferPool().getNumActive());
          this.temp.append(", Num Idle: ");
          this.temp.append(target.getByteBufferPool().getNumIdle());
          this.temp.append(", Max Idle: ");
          this.temp.append(target.getBasicConfig().getObjectPoolConfig().getByteBufferObjectPoolConfig().getMaxIdle());
          this.temp.append(", Max Active: ");
          this.temp.append(target.getBasicConfig().getObjectPoolConfig().getByteBufferObjectPoolConfig().getMaxActive());
        } else {
          this.temp.append("Byte Buffer Pool - Closed");
        } 
      } else {
        this.temp.append("Byte Buffer Pool - Not Used");
      } 
      handler.sendClientMsg(this.temp.toString());
      this.temp.setLength(0);
      
      if (target.getClientDataPool() != null) {
        if (PoolHelper.isPoolOpen(target.getClientDataPool())) {
          this.temp.append("Client Data Pool - ");
          this.temp.append("Num Active: ");
          this.temp.append(target.getClientDataPool().getNumActive());
          this.temp.append(", Num Idle: ");
          this.temp.append(target.getClientDataPool().getNumIdle());
          this.temp.append(", Max Idle: ");
          this.temp.append(target.getBasicConfig().getObjectPoolConfig().getClientDataObjectPoolConfig().getMaxIdle());
          this.temp.append(", Max Active: ");
          this.temp.append(target.getBasicConfig().getObjectPoolConfig().getClientDataObjectPoolConfig().getMaxActive());
        } else {
          this.temp.append("Client Data Pool - Closed");
        } 
      } else {
        this.temp.append("Client Data Pool - Not Used");
      } 
      handler.sendClientMsg(this.temp.toString());
      this.temp.setLength(0);
      
      handler.sendClientMsg("."); return;
    } 
    if (cmd.equals("set")) {
      if (param.length < 3) {
        handler.sendClientMsg("-ERR insufficient param");
        return;
      } 
      if (param[2].equals("null"))
        param[2] = null; 
      try {
        if (param[1].equals("maxClient")) {
          long no = Long.parseLong(param[2]);
          target.setMaxConnection(no);
        } else if (param[1].equals("maxClientMsg")) {
          target.setMaxConnectionMsg(param[2]);
        } else if (param[1].equals("port")) {
          long no = Long.parseLong(param[2]);
          target.setPort((int)no);
        } else if (param[1].equals("port")) {
          long no = Long.parseLong(param[2]);
          target.setPort((int)no);
        } else if (param[1].equals("maxAuthTry")) {
          int no = Integer.parseInt(param[2]);
          target.setMaxAuthTry(no);
        } else if (param[1].equals("maxAuthTryMsg")) {
          target.setMaxAuthTryMsg(param[2]);
        } else if (param[1].equals("clientEventHandler")) {
          target.setClientEventHandler(param[2]);
        } else if (param[1].equals("clientCommandHandler")) {
          target.setClientCommandHandler(param[2]);
        } else if (param[1].equals("clientWriteHandler")) {
          target.setClientWriteHandler(param[2]);
        } else if (param[1].equals("clientObjectHandler")) {
          target.setClientObjectHandler(param[2]);
        } else if (param[1].equals("clientAuthenticationHandler")) {
          target.setClientAuthenticationHandler(param[2]);
        } else if (param[1].equals("clientData")) {
          target.setClientData(param[2]);
        } else if (param[1].equals("clientExtendedEventHandler")) {
          target.setClientExtendedEventHandler(param[2]);
        } else if (param[1].equals("timeout")) {
          long no = Long.parseLong(param[2]);
          target.setTimeout((int)no);
        } else if (param[1].equals("timeoutMsg")) {
          target.setTimeoutMsg(param[2]);
        } else if (param[1].equals("plugin")) {
          if (param[0].equals("self")) {
            try {
              adminServer.setCommandPlugin(param[2]);
            } catch (Exception e) {
              handler.sendClientMsg("-ERR not set : " + e);
              return;
            } 
          } else {
            handler.sendClientMsg("-ERR Bad target : " + param[0] + " self is only allowed.");
            return;
          } 
        } else if (param[1].equals("consoleLoggingFormatter")) {
          target.setConsoleLoggingFormatter(param[2]);
        } else if (param[1].equals("consoleLoggingLevel")) {
          if (param[2].endsWith("SEVERE")) {
            target.setConsoleLoggingLevel(Level.SEVERE);
          } else if (param[2].endsWith("WARNING")) {
            target.setConsoleLoggingLevel(Level.WARNING);
          } else if (param[2].endsWith("INFO")) {
            target.setConsoleLoggingLevel(Level.INFO);
          } else if (param[2].endsWith("CONFIG")) {
            target.setConsoleLoggingLevel(Level.CONFIG);
          } else if (param[2].endsWith("FINE")) {
            target.setConsoleLoggingLevel(Level.FINE);
          } else if (param[2].endsWith("FINER")) {
            target.setConsoleLoggingLevel(Level.FINER);
          } else if (param[2].endsWith("FINEST")) {
            target.setConsoleLoggingLevel(Level.FINEST);
          } else if (param[2].endsWith("ALL")) {
            target.setConsoleLoggingLevel(Level.ALL);
          } else if (param[2].endsWith("OFF")) {
            target.setConsoleLoggingLevel(Level.OFF);
          } else {
            handler.sendClientMsg("-ERR Bad Level " + param[2]);
            return;
          } 
        } else if (param[1].equals("loggingLevel")) {
          if (param[2].endsWith("SEVERE")) {
            target.setLoggingLevel(Level.SEVERE);
          } else if (param[2].endsWith("WARNING")) {
            target.setLoggingLevel(Level.WARNING);
          } else if (param[2].endsWith("INFO")) {
            target.setLoggingLevel(Level.INFO);
          } else if (param[2].endsWith("CONFIG")) {
            target.setLoggingLevel(Level.CONFIG);
          } else if (param[2].endsWith("FINE")) {
            target.setLoggingLevel(Level.FINE);
          } else if (param[2].endsWith("FINER")) {
            target.setLoggingLevel(Level.FINER);
          } else if (param[2].endsWith("FINEST")) {
            target.setLoggingLevel(Level.FINEST);
          } else if (param[2].endsWith("ALL")) {
            target.setLoggingLevel(Level.ALL);
          } else if (param[2].endsWith("OFF")) {
            target.setLoggingLevel(Level.OFF);
          } else {
            handler.sendClientMsg("-ERR Bad Level " + param[2]);
            return;
          } 
        } else if (param[1].equals("communicationLogging")) {
          if (param[2].equals("true"))
          { target.setCommunicationLogging(true); }
          else
          { target.setCommunicationLogging(false); } 
        } else if (param[1].equals("objectPoolConfig-maxActive")) {
          int no = Integer.parseInt(param[2]);
          target.getConfig().getObjectPoolConfig().setMaxActive(no);
        } else if (param[1].equals("objectPoolConfig-maxIdle")) {
          int no = Integer.parseInt(param[2]);
          target.getConfig().getObjectPoolConfig().setMaxIdle(no);
        } else if (param[1].equals("objectPoolConfig-initSize")) {
          int no = Integer.parseInt(param[2]);
          target.getConfig().getObjectPoolConfig().setInitSize(no);
        } else {
          handler.sendClientMsg("-ERR Bad Set Key : " + param[1]);
          return;
        } 
        handler.sendClientMsg("+OK Set");
      } catch (Exception e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("get")) {
      if (param.length < 2) {
        handler.sendClientMsg("-ERR insufficient param");
        return;
      } 
      try {
        if (param[1].equals("maxClient")) {
          long no = target.getMaxConnection();
          handler.sendClientMsg("+OK " + no);
        } else if (param[1].equals("maxClientMsg")) {
          String msg = target.getMaxConnectionMsg();
          msg = MyString.replaceAll(msg, "\n", "\\n");
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("port")) {
          long no = target.getPort();
          handler.sendClientMsg("+OK " + no);
        } else if (param[1].equals("maxAuthTry")) {
          int no = target.getMaxAuthTry();
          handler.sendClientMsg("+OK " + no);
        } else if (param[1].equals("maxAuthTryMsg")) {
          String msg = target.getMaxAuthTryMsg();
          msg = MyString.replaceAll(msg, "\n", "\\n");
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientEventHandler")) {
          String msg = target.getClientEventHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientCommandHandler")) {
          String msg = target.getClientCommandHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientWriteHandler")) {
          String msg = target.getClientWriteHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientObjectHandler")) {
          String msg = target.getClientObjectHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientAuthenticationHandler")) {
          String msg = target.getClientAuthenticationHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientData")) {
          String msg = target.getClientData();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("clientExtendedEventHandler")) {
          String msg = target.getClientExtendedEventHandler();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("timeout")) {
          int j = target.getTimeout();
          handler.sendClientMsg("+OK " + j);
        } else if (param[1].equals("timeoutMsg")) {
          String msg = target.getTimeoutMsg();
          msg = MyString.replaceAll(msg, "\n", "\\n");
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("plugin")) {
          if (param[0].equals("self")) {
            String msg = adminServer.getCommandPlugin();
            handler.sendClientMsg("+OK " + msg);
          } else {
            handler.sendClientMsg("-ERR Bad target : " + param[0] + " self is only allowed.");
          } 
        } else if (param[1].equals("consoleLoggingFormatter")) {
          String msg = target.getConsoleLoggingFormatter();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("consoleLoggingLevel")) {
          String msg = target.getConsoleLoggingLevel();
          handler.sendClientMsg("+OK " + msg);
        } else if (param[1].equals("serviceState")) {
          int state = target.getServiceState();
          if (state == 1)
          { handler.sendClientMsg("+OK INIT"); }
          else if (state == 5)
          { handler.sendClientMsg("+OK RUNNING"); }
          else if (state == 0)
          { handler.sendClientMsg("+OK STOPPED"); }
          else if (state == 2)
          { handler.sendClientMsg("+OK SUSPENDED"); }
          else
          { handler.sendClientMsg("+OK UNKNOWN"); } 
        } else if (param[1].equals("communicationLogging")) {
          boolean bool = target.getCommunicationLogging();
          handler.sendClientMsg("+OK " + bool);
        } else if (param[1].equals("objectPoolConfig-maxActive")) {
          int j = target.getConfig().getObjectPoolConfig().getMaxActive();
          handler.sendClientMsg("+OK " + j);
        } else if (param[1].equals("objectPoolConfig-maxIdle")) {
          int j = target.getConfig().getObjectPoolConfig().getMaxIdle();
          handler.sendClientMsg("+OK " + j);
        } else if (param[1].equals("objectPoolConfig-initSize")) {
          int j = target.getConfig().getObjectPoolConfig().getInitSize();
          handler.sendClientMsg("+OK " + j);
        } else {
          handler.sendClientMsg("-ERR Bad Get Key : " + param[1]);
        } 
      } catch (Exception e) {
        handler.sendClientMsg("-ERR " + e);
      }  return;
    } 
    if (cmd.equals("kill-clients-all")) {
      
      ObjectPool objectPool = target.getClientHandlerPool();
      
      if (PoolHelper.isPoolOpen(objectPool)) {
        if (!QSObjectPool.class.isInstance(objectPool)) {
          handler.sendClientMsg("-ERR System Error!");
        }
        
        ClientIdentifier clientIdentifier = target.getClientIdentifier();
        ClientHandler foundClientHandler = null;
        synchronized (clientIdentifier.getObjectToSynchronize()) {
          Iterator<ClientHandler> iterator = clientIdentifier.findAllClient();
          handler.sendClientMsg("+OK closing");
          int count = 0;
          int found = 0;
          while (iterator.hasNext()) {
            foundClientHandler = iterator.next();
            found++;
            if (!foundClientHandler.isClosed()) {
              foundClientHandler.closeConnection();
              count++;
            } 
          } 
          handler.sendClientMsg("Count Found: " + found);
          handler.sendClientMsg("Count Closed: " + count);
        } 
        handler.sendClientMsg(".");
      } else {
        handler.sendClientMsg("-ERR Closing");
      }  return;
    } 
    if (cmd.equals("kill-client-with")) {
      
      if (param.length < 2) {
        handler.sendClientMsg("-ERR insufficient param");
        return;
      } 
      String search = param[1];
      
      ObjectPool objectPool = target.getClientHandlerPool();
      
      if (PoolHelper.isPoolOpen(objectPool)) {
        if (!QSObjectPool.class.isInstance(objectPool)) {
          handler.sendClientMsg("-ERR System Error!");
        }
        
        ClientIdentifier clientIdentifier = target.getClientIdentifier();
        ClientHandler foundClientHandler = null;
        synchronized (clientIdentifier.getObjectToSynchronize()) {
          Iterator<ClientHandler> iterator = clientIdentifier.findAllClient();
          handler.sendClientMsg("+OK closing");
          int count = 0;
          int found = 0;
          while (iterator.hasNext()) {
            foundClientHandler = iterator.next();
            if (foundClientHandler.toString().indexOf(search) != -1) {
              found++;
              if (!foundClientHandler.isClosed()) {
                foundClientHandler.closeConnection();
                count++;
              } 
            } 
          } 
          handler.sendClientMsg("Count Found: " + found);
          handler.sendClientMsg("Count Closed: " + count);
        } 
        handler.sendClientMsg(".");
      } else {
        handler.sendClientMsg("-ERR Closing");
      } 
      return;
    } 
    handler.sendClientMsg("-ERR Bad Command : " + cmd);
  }
  
  public void closingDev(ClientHandler handler, String uniqueCode) throws IOException {}
  
  public void lostDev(ClientHandler handler, String uniqueCode) throws IOException {}
}
